import Observer  from "./Observer.js";

export default class Vue{

    constructor(obj){

        // 1、初始化事件和生命周期 init events 和 init cycle
        this.beforeCreate = obj.beforeCreate;
        this.created = obj.created;
        this.beforeMount = obj.beforeMount;
        this.mounted = obj.mounted;
        this.beforeUpdate = obj.beforeUpdate;
        this.updated = obj.updated;

        //2、 第一个钩子函数：调用beforeCreate。
        this.beforeCreate && this.beforeCreate();

        //3、第一个阶段：数据挂载：把配置项（构造函数参数）中data的属性赋给vue对象
        this.$data = obj.data;//vue内部把大部分根属性挂载在vue对象本身上，属性名前面加上$
        for(let key in obj.data){ 
            // 订阅
             // 1、订阅，遍历dom，完成订阅
             let obserser = new Observer();

             let rootDom = document.querySelector(obj.el);
 
             for(let i=0;i<rootDom.children.length;i++){
                 if(rootDom.children[i].innerHTML.includes("{{"+key+"}}")){       
 
                     let oldHTML = rootDom.children[i].innerHTML;
 
                     obserser.addSubscriber(function(newVal){                      
                         rootDom.children[i].innerHTML = oldHTML.replace(new RegExp("{{"+key+"}}","g"),newVal);
                     })
 
                 }
             }

            let value = obj.data[key];
            Object.defineProperty(this,key,{
                set:function(newVal){
                    if(value===newVal){
                        return;
                    }
                    value = newVal;
                    console.log(key+"被改了",newVal);

                    this.beforeUpdate && this.beforeUpdate();

                    // 第三个阶段：模板更新
                    // 发布：修改模板
                    obserser.publish(newVal);

                    this.updated&& this.updated();
                },
                get:function(){
                    return value;
                }
            })

        }

        // 4、第一个钩子函数：
        this.created && this.created();


        // 5、检查el，template
        if(obj.el){
            this.$el = obj.el;
            if(obj.template){

            }
        }

        // 6、
        this.beforeMount&&this.beforeMount();


        // 7、第二个阶段：模板编译：
        this.render();


        // 8、
        this.mounted && this.mounted();

    }

    render(){

        let sourceHTML = document.querySelector(this.$el).innerHTML;
        for(let key in this.$data){
            sourceHTML = sourceHTML.replace(new RegExp("{{"+key+"}}","g"),this.$data[key]);
        }
        
        document.querySelector(this.$el).innerHTML = sourceHTML;

        
    }

}